#include <ioCC2540.h>
#include "iic.h"

#define  uchar unsigned  char 
#define  uint  unsigned  int
void IIC_Init(void)
{
    P1DIR |= 0x60;      
    SDA = 1;
    delay_1ms();
    SCL = 1;
    delay_1ms();
}
void Signal_Start(void)
{
    P1DIR |= 0x60;      
    SDA = 1;
    delay_1ms();
    SCL = 1;
    delay_1ms();
    SDA = 0;
    delay_1ms(); 
}
void Signal_Stop(void)
{
    P1DIR |= 0x60;    
    SDA = 0;
    delay_1ms();
    SCL = 1;
    delay_1ms();
    SDA = 1;
    delay_1ms(); 
}
void Respons(void)
{
    uint i = 0;

    P1DIR |= 0x20;      
    P1DIR &= ~0x40;      

    SCL = 1;
    delay_1ms();
    SCL = 0;
    delay_1ms();
    
    if(i>=300)
    {
      delay_1ms();
    }
}
void Write_Byte(uchar wdata)
{
    uchar i,mdata;

    P1DIR |= 0x60;      
    mdata = wdata;
    for(i=0;i<8;i++)
    {        
        SCL = 0;
        delay_1ms();
        if(mdata & 0x80)
        {
          SDA = 1;
        }
        else
        {
          SDA = 0;
        }
        delay_1ms();
        SCL = 1;
        delay_1ms();  
        mdata <<= 1;
    }
    SCL = 0;
    delay_1ms();
    SCL = 1;
    delay_1ms();
}
uchar Read_Byte()
{
    uchar i,rdata = 0;

    P1DIR |= 0x20;      
    P1DIR &= ~0x40;     

    SCL = 0;
    delay_1ms();
    SCL = 1;
    for(i=0;i<8;i++)
    {
        SCL = 1;
        delay_1ms();
        rdata = (rdata<<1)|SDA;
        SCL = 0;
        delay_1ms();
    }
    return rdata;
}
void Write_Add(uchar add,uchar wdata,uchar comd)
{
    Signal_Start(); 
    Write_Byte(comd);
    Respons();      
    Write_Byte(add);
    Respons();      
    Write_Byte(wdata);
    Respons();     
    Signal_Stop(); 
}
uchar Read_Add(uchar add,uchar comd)
{
    uchar tdata;
    Signal_Start();     
    Write_Byte(comd);
    Respons();          
    Write_Byte(add);
    Respons();          
    Signal_Start();     
    Write_Byte(comd|0x01);
    Respons();         
    tdata = Read_Byte();
    Signal_Stop();      
    return tdata;       
}
void delay_1ms(void)   
{
    int a=2,b=4;
    for(;a>0;a--)
    {
        for(;b>0;b--);  
    }
}
